package com.jimo.basetools.utils;

import com.jimo.basetools.constants.Constants;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
 * <p>Title: AesUtils</p>
 * <p>Description: AES加密解密</p>
 * @author JIMO
 * @date 2023年5月5日
 */
public class AesUtils {

	/** 参数分别代表 算法名称/加密模式/数据填充方式 */
    private static final String ALGO_RITHM_STR = "AES/ECB/PKCS5Padding";
	
	/**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) {
    	
    	if (StringUtils.isEmpty(content)) {
    		return null;
    	}
    	
    	try {
	        KeyGenerator kgen = KeyGenerator.getInstance("AES");
	        kgen.init(128);
	        Cipher cipher = Cipher.getInstance(ALGO_RITHM_STR);
	        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
	        byte[] b = cipher.doFinal(content.getBytes(Constants.UTF_8));
	        // 采用base64算法进行转码,避免出现中文乱码
	        return Base64.encodeBase64String(b);
    	} catch (Exception e) {
    		e.printStackTrace();
    		return null;
    	}
 
    }
 
    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) {
    	
    	if (StringUtils.isEmpty(encryptStr)) {
    		return null;
    	}
    	
    	try {
	        KeyGenerator kgen = KeyGenerator.getInstance("AES");
	        kgen.init(128);
	        Cipher cipher = Cipher.getInstance(ALGO_RITHM_STR);
	        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
	        // 采用base64算法进行转码,避免出现中文乱码
	        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
	        byte[] decryptBytes = cipher.doFinal(encryptBytes);
	        return new String(decryptBytes);
    	} catch (Exception e) {
    		e.printStackTrace();
    		return null;
    	}
    }
	
}
